﻿/******************************************************************************
 * 创建者：gtts
 * 创建日期：2011.4.5
 * 类名：Utility
 * 说明：常用的工具类集合
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using System.Text.RegularExpressions;

namespace GttsWebLibrary
{
    /// <summary>
    /// 常用的工具类集合
    /// </summary>
    public class Utility
    {
        /// <summary>
        /// 返回网站应用程序的路径
        /// 例如：如果应用程式是根目录，则返回"/";
        ///  如果应用程式是其他虚拟目录，则返回"/Virtual Path/"
        /// </summary>
        /// <returns>返回应用程式的路径</returns>
        public static string ApplicationPath
        {
            get
            {
                string applicationPath = HttpContext.Current.Request.ApplicationPath;
                if (applicationPath != "/")
                {
                    applicationPath = applicationPath + "/";
                }
                return applicationPath;
            }
        }
        /// <summary>
        /// 返回应用程序的路径
        /// 例如：如果应用程式是根目录，则返回"https://www.domain.com/";
        ///  如果应用程式是其他虚拟目录，则返回"https://www.domain.com/Virtual Path/"
        /// </summary>
        /// <returns>返回应用程式的路径</returns>
        public static string ApplicationSSLPath
        {
            //TODO:返回应用程序的路径,形如"https://www.domain.com/";
            get
            {
                bool useSSL = false;
                try
                {
                    // useSSL = Convert.ToBoolean(ConfigurationSettings.AppSettings["UseSSL"]);
                }
                catch
                {
                    useSSL = false;
                }

                return "http" + (useSSL ? "s" : "") + "://" + HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString().ToLower() + ApplicationPath;
            }
        }

        /// <summary>
        /// 当前的用户
        /// </summary>
        public static object CurrentUser
        {
            get
            {
                //UserToken token = (UserToken)System.Web.HttpContext.Current.Session["UserToken"];
                //if (token == null)
                //{
                //    FormsAuthentication.SignOut();
                //    HttpContext.Current.Response.Redirect(Utility.ApplicationPath + "Security/SignIn.aspx");
                //}
                //return token;
                //TODO：当前的用户(返回用户实体)
                return null;
            }
        }

        /// <summary>
        /// 当前的用户权限
        /// </summary>
        public static object CurrentPermissions
        {
            get
            {
                //UserPermissions permission = (UserPermissions)HttpContext.Current.Session["UserPermissions"];
                //if (permission == null)
                //{
                //    FormsAuthentication.SignOut();
                //    HttpContext.Current.Response.Redirect(Utility.ApplicationPath + "Security/SignIn.aspx");
                //}
                //return permission;
                //TODO：当前的用户权限(返回用户实体)
                return null;
            }
        }


        /// <summary>
        /// 对一个字符串进行剪切，对多于该字符数的用"..."表示，则以ToolTip进行提示
        /// </summary>
        /// <param name="sValue">要剪切的字符串</param>
        /// <param name="size">要保留的字符数</param>
        /// <returns>返回剪切好的及ToolTip的整个Html格式的字符串</returns>
        public static string CutString(string sValue, int size)
        {
            return CutString(sValue, size, "...");
        }
        /// <summary>
        /// 对一个字符串进行剪切，对多于该字符数的用指定字符串表示，则以ToolTip进行提示
        /// </summary>
        /// <param name="sValue">要剪切的字符串</param>
        /// <param name="size">要保留的字符数</param>
        /// <param name="flag">指定替换字符串（比如"..."）</param>
        /// <returns>返回剪切好的及ToolTip的整个Html格式的字符串</returns>
        public static string CutString(string sValue, int size, string flag)
        {
            string m_retu = "";
            if (sValue.Length > size)
            {
                m_retu = "<span title=" + HttpContext.Current.Server.HtmlDecode(sValue) + ">"
                    + HttpContext.Current.Server.HtmlEncode(sValue.Substring(0, size)) + flag
                    + "</span>";
            }
            else
            {
                m_retu = sValue;
            }
            return m_retu;
        }

        /// <summary>
        /// 如果有什么信息在客户的弹出的，则调用此函数
        /// </summary>
        /// <param name="message">要弹出的消息</param>
        public static void ShowMessage(string message)
        {
            string script = "<script>"
                + "alert('" + message + "');"
                + "</script>";
            HttpContext.Current.Response.Write(script);
        }

        /// <summary>
        /// 把文本框的内容格式成相应的Html在网页中显示
        /// </summary>
        /// <param name="sValue">要格式的字符串</param>
        /// <returns>格式好的Html字符串</returns>
        public static string ToHtml(string sValue)
        {
            //TODO:把文本框的内容格式成相应的Html在网页中显示(只给出了形式，没有完善)
            string m_retu = "";
            if (sValue != null)
            {
                m_retu = HttpUtility.HtmlEncode(sValue);
                m_retu = m_retu.Replace(" ", "<br />");
                m_retu = m_retu.Replace(" ", "<br />");
                m_retu = m_retu.Replace(" ", "<br />");
            }
            return m_retu;
        }


        /// <summary>
        /// 加入一些用户信息到记录行中
        /// 如果是新增的，则加入以下内容：新增的初始信息和修改的初始信息
        /// 如果是修改的，则加入以下内容：修改的初始信息
        /// </summary>
        /// <param name="m_dr">要加入记录的行</param>
        /// <param name="isInsert">是否为新增</param>
        public static void AddUserInfoToRow(System.Data.DataRow m_dr, bool isInsert)
        {
            //TODO:加入一些用户信息到记录行中
            if (isInsert)
            {
                //if (m_dr.Table.Columns.Contains("StateCode"))
                //{
                //    m_dr["StateCode"] = 1; //处于初始状态
                //}
                //m_dr["ModifiedBy"] = CurrentUser.EntityID;
                //m_dr["ModifiedOn"] = DateTime.UtcNow;
                //m_dr["ModifiedbyName"] = CurrentUser.EntityAlias;
                //m_dr["CreatedBy"] = CurrentUser.EntityID;
                //m_dr["CreatedOn"] = DateTime.UtcNow;
                //m_dr["CreatedbyName"] = CurrentUser.EntityAlias;
                //m_dr["DeletionStateCode"] = 0;
                //try
                //{
                //    m_dr["OwningUser"] = CurrentUser.EntityID;
                //}
                //catch { }
            }
            else
            {

                //m_dr["ModifiedBy"] = CurrentUser.EntityID;
                //m_dr["ModifiedOn"] = DateTime.UtcNow;
                //m_dr["ModifiedbyName"] = CurrentUser.EntityAlias;
            }
        }

        /// <summary>
        /// 把URL格式转换成可以点击的URL内容
        /// </summary>
        /// <param name="url">要连接的URL地址</param>
        /// <param name="DisplayName">显示到界面的内容</param>
        /// <returns>已格式好的字符串</returns>
        public static string GetURLDisplayString(string url, string DisplayName)
        {
            if (url == "") return "";
            if (url.Length >= 7)
            {
                if (url.Substring(0, 7).ToUpper() != "HTTP://")
                {
                    url = "Http://" + url;
                }
            }

            if (DisplayName.Length > 15)
            {
                DisplayName = DisplayName.Substring(0, 15) + "...";
            }

            return "<a href='" + url + "' target='_blank'>" + DisplayName + "</a>";
        }

        /// <summary>
        /// 把Email格式成可点击的Email显示格式
        /// </summary>
        /// <param name="email">Email地址</param>
        /// <returns>已格式好的字符串</returns>
        public static string GetEmailDisplayValue(string email)
        {
            if (email.Trim() == "") return "";
            return "<a href='mailto:" + email + "'>" + email + "</a>";
        }

        /// <summary>
        /// 得到页面的背景颜色
        /// </summary>
        /// <returns></returns>
        public static string GetPageBgColorFormat()
        {
            // return System.Drawing.Color.FromArgb(240,240,240);
            return "White";
        }

        /// <summary>
        /// 取回电话组合的格式
        /// </summary>
        /// <param name="phoneCountryKey">电话的国家码</param>
        /// <param name="phoneAreaKey">电话的地址码</param>
        /// <param name="phoneKey">电话号码</param>
        /// <param name="phoneExtKey">分号</param>
        /// <returns>返回组合好的电话格式</returns>
        public static string GetPhoneFormat(string phoneCountryKey, string phoneAreaKey, string phoneKey, string phoneExtKey)
        {
            string strRetu = "";

            if (phoneCountryKey != null && phoneCountryKey != string.Empty)
            {
                strRetu = phoneCountryKey;
            }
            if (phoneAreaKey != null && phoneAreaKey != string.Empty)
            {
                strRetu += "(" + phoneAreaKey + ")";
            }
            if (phoneKey != null && phoneKey != string.Empty)
            {
                strRetu += phoneKey;
            }
            if (phoneExtKey != null && phoneExtKey != string.Empty)
            {
                strRetu += " Ext " + phoneExtKey;
            }
            return strRetu;
        }

        public static string GetPhoneFormat(object phoneCountryKey, object phoneAreaKey, object phoneKey, object phoneExtKey)
        {
            string strRetu = "";

            if (phoneCountryKey != null && phoneCountryKey.ToString() != string.Empty)
            {
                strRetu = phoneCountryKey.ToString();
            }
            if (phoneAreaKey != null && phoneAreaKey.ToString() != string.Empty)
            {
                strRetu += "(" + phoneAreaKey.ToString() + ")";
            }
            if (phoneKey != null && phoneKey.ToString() != string.Empty)
            {
                strRetu += phoneKey.ToString();
            }
            if (phoneExtKey != null && phoneExtKey.ToString() != string.Empty)
            {
                strRetu += " Ext " + phoneExtKey.ToString();
            }
            return strRetu;
        }

        /// <summary>
        /// 取得utc时间的当地时间
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetUtcLocalString(object obj)
        {
            DateTime d = Convert.ToDateTime(obj);
            return GetUtcLocalString(d, "d");

        }

        /// <summary>
        /// by hjs 2004-10-20 取得utc时间的当地时间
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetUtcLocalString(DateTime d)
        {
            return GetUtcLocalString(d, "d");

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="d">a DateTime value</param>
        /// <param name="outputFormat">'d', 't', 'g', or 'gbr'</param>
        /// <returns></returns>
        public static string GetUtcLocalString(DateTime d, string outputFormat)
        {
            string localTimeFormat = "<script>document.write(ebcUTC2Loc({0},{1},{2},{3},{4},{5},'" + outputFormat + "'));</script>";
            return string.Format(localTimeFormat, d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);

        }


        public static void ParsePartNumber(string partNumber, ref string prefix, ref string partBase, ref string partitionSupport)
        {
            if (partNumber == null || partNumber == string.Empty)
            {
                prefix = string.Empty;
                partBase = string.Empty;
                partitionSupport = string.Empty;
                return;
            }
            Regex regex = new Regex("[0-9]");
            Match match = regex.Match(partNumber);
            if (match.Success)
            {
                prefix = partNumber.Substring(0, match.Index);
                partBase = partNumber.Substring(match.Index);
                partitionSupport = partNumber.Substring(match.Index, 1);
            }
            else
            {
                prefix = partNumber;
                partitionSupport = "-1";
            }

        }

    }
}
